<template>
  <view>
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <loading :showLoaded.sync="showLoaded"></loading>
    <view class="special-sale">
      <specialEntrance v-if="identifier && !showLoaded" :preview.sync="preview" :identifier.sync="identifier"
        @timeup='timeup' @clickListEntrance='clickListEntrance'>
      </specialEntrance>
    </view>
    <register-widget ref="registerWidgetRef" location="special" :tsActId="tsActId" />
  </view>
</template>

<script>
  import api from '@/api/api';
  import tip from '@/utils/tip';
  import {
    CART_KEY,
    SYSTEM_INFO,
    USER_SPECICAL_INFO,
    MERCHANT_INFO,
    CUSTOMER_INFO,
    LOWER_WX_VERSION,
    MEMBER_INFO,
    USER_INFO
  } from '@/utils/constant';
  import NavBar from '@/components/common/navbar';
  import specialEntrance from "../../components/wxparse/wxparse.vue";
  import Loading from '@/components/common/loading';
  import util from '@/utils/util.js';
  import cmsMethods from '@/utils/cmsItems.js';
  import registerWidget from "@/components/register/register-widget.vue"
  import {
    getActivitySubscribeTemplate
  } from '@/utils/commonActItems.js'
  export default {
    components: {
      navBar: NavBar,
      specialEntrance: specialEntrance,
      loading: Loading,
      registerWidget: registerWidget,
    },
    data() {
      return {
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          navbarTitle: '',
          isTopFixed: true,
          hideSearch: true,
          hideHome: true,
          whiteIcon: 1,
        },
        isShowCustomNavBar: true,
        tsActId: 0,
        showLoaded: true,
        nowPages: '',
        isFullOld: false, //默认不显示18周岁授权弹层
        startTime: '',
        preStartTime: '',
        endTime: '',
        requestEnd: false,
        specialCmsInfo: {},
        isHidePage: false,
        specialSaleInfo: {},
        identifier: '',
        newActId: 202,
        subscribeCode: 88,
        subCheck: false,
        showBook: false,
        alreadySubScribe: false
      }
    },

    async onLoad(option) {
      this.tsActId = option.tsActId;

      let pages = getCurrentPages();
      var currPage = pages[pages.length - 1];
      this.nowPages = currPage.route;
    },
    onHide() {
      this.showLoaded = true
      this.isHidePage = true
    },
    onShow: async function() {
      await this.$onLaunched;
      getApp().cl_tracker.track('mini_program_view', {
        path: this.nowPages,
        pageName: '特殊购买',
      })
      if (!!this.isHidePage) {
        this.showLoaded = false
        this.isHidePage = false
      }
      this.getTsInfoNoLogin(this.tsActId)
      this.$commonSensors.commonPageView('SpecialPurchasedPageView')
    },

    methods: {
      timeup() {
        this.identifier = 'cms/specialentrance' + this.tsActId
      },
      clickListEntrance(c_from) {
        //特邀会员限时专场详情页
        let {
          tsActId,
          name,
          listPath
        } = uni.getStorageSync('TsInfo');
        let params = {
          "c_from": '活动页',
          "c_campaignID": tsActId,
          "c_campaignName": name
        }
        getApp().commonClTrack('c_ebmp_home_member_campaign_click_enter', params);

        uni.navigateTo({
          url: listPath
        })
      },
      getTsById: function(id) {
        this.$commonFunction.getTsById(id).then((result) => {
          this.specialSaleInfo = result
          this.statusControl(result)
        }).catch(() => {
          setTimeout(() => {
            this.showLoaded = false
          }, 500)
          uni.reLaunch({
            url: `/pages/home/home?tsActId=${id}`
          });
        })
      },
      statusControl(result) {
        let {
          status,
          showInHome,
          campaignTargetSaleId
        } = result
        if (status == 5) {
          this.identifier = 'cms/prespecialentrance' + campaignTargetSaleId
        } else if (status == 6) {
          let storgeText = 'hasVisitTS' + campaignTargetSaleId
          if (!uni.getStorageSync(storgeText)) {
            uni.setStorageSync(storgeText, true)
          }
          this.identifier = 'cms/specialentrance' + campaignTargetSaleId
        } else {
          uni.reLaunch({
            url: `/pages/home/home?tsActId=${campaignTargetSaleId}`
          });

        }
        let advDialog = 'cms/specialsale/adv' + campaignTargetSaleId
        // 这边存缓存就一链路，扫码进来规规矩矩按流程走没去首页，pdp查看活动规则，订单提交成功回活动页
        this.getCmsPageInfo(advDialog, campaignTargetSaleId)


      },
      getCmsPageInfo(identifier, campaignTargetSaleId) {
        cmsMethods.getCMSPageInfo(identifier).then(res => {
          if (res && res.shareImage) {
            this.specialCmsInfo = util.urlToObj(res.shareTitle)
            this.setSkipInfo(campaignTargetSaleId)
            this.requestEnd = true

          }
        })
      },
      async setSkipInfo(campaignTargetSaleId) {
        setTimeout(() => {
          this.showLoaded = false
        }, 500)
        let obj = {}
        let url;
        let {
          hideBack,
          rulePath
        } = this.specialCmsInfo
        let id = campaignTargetSaleId

        if (hideBack == 'true') {
          obj.hideBack = true
        } else {
          obj.hideBack = false
        }
        obj.rulePath = rulePath
        if (this.specialSaleInfo.applySkuCodes.length > 1) {
          obj.listPath = `/pages/special/specialList?tsActId=${id}`
        } else {
          obj.listPath = await this.getAllGoodsList(this.specialSaleInfo.applySkuCodes[0])
        }
        obj.landPath = `/pages/special/specialSale?tsActId=${id}`
        obj.tsActId = id
        obj.name = this.specialSaleInfo.name
        uni.setStorageSync('TsInfo', obj)

      },
      async getAllGoodsList(code) {
        let path;
        try {
          let merchantInfo = uni.getStorageSync("merchantInfo");
          let memberDetails = uni.getStorageSync("memberDetails");
          const json = await api.getAllGoodsList({
            query: {
              q: code,
              class_id: "",
              page_no: 1,
              page_size: 1,
              store_id: merchantInfo.cloudMerchantStoreId,
              merchant_id: merchantInfo.cloudMerchantId,
              group_id: !!memberDetails ? memberDetails.customerGroupId : 0,
              member_level_id: !!memberDetails ? memberDetails.memberLevelId : 0,
              member_status: !!memberDetails ? memberDetails.isActive : "Inactive",
            },
          })
          if (json.code === 1000) {
            let item = json.data.content[0]
            path = `/pages/item/item?id=${item.itemId}&valueId=${item.valueId}`
          }
          return path
        } catch (err) {

        }
      },
      getTsInfoNoLogin: function(id) {
        this.$commonFunction.commonLoginNew().then((res) => {
          const customerInfo = res.data;
          //未入会自动跳首页
          if (!customerInfo.jwt) {
            this.getInfo(id)
          } else {
            this.getTsById(id)
          }
        }).catch(() => {
          this.getInfo(id)
        })
      },
      async getInfo(id) {
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        const result = await api.getTsInfoNoLogin({
          method: 'GET',
          query: {
            "merchant_id": merchantInfo.cloudMerchantId,
          },
        }, id);
        if (result.code == 1000) {
          let {
            status,
            showInHome
          } = result.data
          this.specialSaleInfo = result.data
          let tsAdvDialogCms = 'cms/specialsale/adv' + id
          let tsPreAdvDialogCms = 'cms/specialsale/pradv' + id
          if (status == 5 && !!showInHome) {
            this.identifier = 'cms/prespecialentrance' + id
            uni.reLaunch({
              url: `/pages/home/home?tsActId=${id}`
            });
          } else if (status == 6 && !!showInHome) {
            this.identifier = 'cms/specialentrance' + id
            uni.reLaunch({
              url: `/pages/home/home?tsActId=${id}`
            });
          } else {
            uni.reLaunch({
              url: `/pages/home/home?tsActId=${id}`
            });
          }
        } else {
          uni.reLaunch({
            url: `/pages/home/home?tsActId=${id}`
          });
        }
        setTimeout(() => {
          this.showLoaded = false
        }, 500)
      }

    }
  }
</script>

<style lang="less">
  .hide {
    opacity: 0;
  }

  .book-content {
    width: 562rpx;
    background: #fff;
    position: relative;

    .checkbox-item {
      display: flex;
      margin-top: 30rpx;
      padding: 0 36rpx;

      .checkbox-text {
        margin-left: 16rpx;
        font-size: 26rpx;
        line-height: 36rpx;
      }
    }
  }

  .special-sale {
    overflow: hidden;

    .button1 {
      color: #1B1B1B;
      font-size: 26rpx;
      width: 28%;
      margin: 0 auto;
      border: 1px solid #a0a0a0;
      height: 72rpx;
      line-height: 70rpx;
      display: inline-block;
      background-color: #fff;
      text-align: center;
      margin-top: 80rpx;
    }
  }
</style>
